package io.renren.api;

import io.renren.entity.Book;
import io.renren.entity.BookVideo;
import io.renren.entity.vo.BookVideo4Web;
import io.renren.service.BookService;
import io.renren.service.BookVideoService;
import io.renren.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: hongyuliu
 * @Date: 2019-06-05
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/resource")
public class APiBookResourceController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookVideoService bookVideoService;

    /**
     * 获取资源列表
     *
     * @return
     */
    @GetMapping("/list/{bookId}")
    public R getResourceList(@PathVariable Long bookId) {

        Book book = bookService.queryObject(bookId);

        //根据教辅书id，获取教辅书列表
        Map videoQuery = new HashMap();
        videoQuery.put("status", "1");
        videoQuery.put("deleted", "0");
        videoQuery.put("bookId", bookId);
        List<BookVideo> bookVideoList = bookVideoService.queryList(videoQuery);
        List<BookVideo4Web> bookVideo4WebList = bookVideoList.stream()
                .map(bookVideo -> {
                    BookVideo4Web bookVideo4Web = new BookVideo4Web();
                    bookVideo4Web.setId(bookVideo.getId());
                    bookVideo4Web.setPageNo(bookVideo.getPageNo());
                    bookVideo4Web.setUnitName(bookVideo.getUnitName());
                    bookVideo4Web.setVideoName(bookVideo.getVideoName());
                    bookVideo4Web.setOrderField(bookVideo.getOrderField() == null ? 0 : bookVideo.getOrderField());
                    return bookVideo4Web;
                })
                .sorted(Comparator.comparing(BookVideo4Web::getPageNo).thenComparing(Comparator.comparing(BookVideo4Web::getOrderField)))
                .collect(Collectors.toList());

        return R.ok().put("resourceList", bookVideo4WebList).put("book", book);
    }

    /**
     * 获取资源详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getResrouceDetail(@PathVariable Long id) {
        BookVideo bookVideo = bookVideoService.queryObject(id);
        return R.ok().put("resourceDetail", bookVideo);
    }
}
